package com.jinsilu.freight.ui.dialog;

import android.content.Context;
import android.view.View;
import android.webkit.WebView;

import com.blankj.utilcode.util.ObjectUtils;
import com.hjq.base.BaseDialog;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.ReplaceHelper;
import com.jinsilu.freight.http.response.DrivingLicenseBean;
import com.jinsilu.freight.http.response.IdCardBean;
import com.jinsilu.freight.http.response.OrderDetailsBean;
import com.jinsilu.freight.http.response.SourceHallBean;
import com.jinsilu.freight.http.response.UserInfoBean;
import com.jinsilu.freight.http.response.VehicleListBean;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Locale;

/**
 * WebView对话框
 */
public final class WebViewDialog {

    public static final class Builder extends UIDialog.Builder<Builder> {

        private OnListener mListener;
        private final WebView mWebView;

        public Builder(Context context) {
            super(context);
            setCustomView(R.layout.dialog_webview);
            mWebView = findViewById(R.id.web_view);
            setWidth(context.getResources().getDisplayMetrics().widthPixels * 85 / 100);
            setConfirm("同意签署");
        }

        public Builder setUrl(String url) {
            mWebView.loadUrl(url);
            return this;
        }

        public Builder setHtmlContent(Context context, OrderDetailsBean mOrderDetails, IdCardBean idCardBean, VehicleListBean vehicleListBean) {

            try {
                // 从assets目录读取HTML文件
                InputStream is = context.getAssets().open("agreement.html");
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                is.close();
                String htmlContent = new String(buffer, "UTF-8");

                UserInfoBean userInfoBean = (UserInfoBean) CommonHelper.getSavedObject("userInfo", UserInfoBean.class);


                Map<String, String> variables = new HashMap<>();
                variables.put("contractNumber", "");
                variables.put("firstParty", String.valueOf("宁夏德泓梦驼铃物流有限责任公司"));
                variables.put("secondParty", String.valueOf(idCardBean.getName()));
                variables.put("idCard", String.valueOf(idCardBean.getIdCard()));
                variables.put("address", String.valueOf(idCardBean.getAddress()));
                variables.put("phone", ReplaceHelper.phoneFormat(userInfoBean.getPhone()));
                variables.put("carNumber", vehicleListBean.getPlateNumber());
                variables.put("color", String.valueOf(""));
                variables.put("originPlace", mOrderDetails.getConsignorAddress());
                
                // 设置当前时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String currentTime = sdf.format(new Date());
                variables.put("startTime", currentTime);
                
                // 设置当前时间+1天
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                String nextDayTime = sdf.format(calendar.getTime());
                variables.put("arrivalTime", nextDayTime);
                
                variables.put("price", String.valueOf(mOrderDetails.getSettlePrice()));
                variables.put("arrivalPlace", mOrderDetails.getConsigneeAddress());
                variables.put("product", mOrderDetails.getGoodsName());

                String content = htmlContent;
                if (variables != null) {
                    for (Map.Entry<String, String> entry : variables.entrySet()) {
                        content = content.replace(entry.getKey(), entry.getValue());
                    }
                }
                mWebView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
            }catch (Exception e){
                e.printStackTrace();
            }

            return this;
        }

        public Builder setHtmlContent(Context context, SourceHallBean mOrderDetails, IdCardBean idCardBean, VehicleListBean vehicleListBean) {

            try {
                // 从assets目录读取HTML文件
                InputStream is = context.getAssets().open("agreement.html");
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                is.close();
                String htmlContent = new String(buffer, "UTF-8");

                UserInfoBean userInfoBean = (UserInfoBean) CommonHelper.getSavedObject("userInfo", UserInfoBean.class);


                Map<String, String> variables = new HashMap<>();
                variables.put("contractNumber", "");
                variables.put("firstParty", String.valueOf("宁夏德泓梦驼铃物流有限责任公司"));
                variables.put("secondParty", String.valueOf(idCardBean.getName()));
                variables.put("idCard", String.valueOf(idCardBean.getIdCard()));
                variables.put("address", String.valueOf(idCardBean.getAddress()));
                variables.put("phone", userInfoBean.getPhone());
                variables.put("carNumber", vehicleListBean.getPlateNumber());
                variables.put("color", String.valueOf(""));
                variables.put("originPlace", mOrderDetails.getConsignorAddress());

                // 设置当前时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String currentTime = sdf.format(new Date());
                variables.put("startTime", currentTime);

                // 设置当前时间+1天
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                String nextDayTime = sdf.format(calendar.getTime());
                variables.put("arrivalTime", nextDayTime);

                variables.put("price", String.valueOf(mOrderDetails.getSettlePrice()));
                variables.put("arrivalPlace", mOrderDetails.getConsigneeAddress());
                variables.put("product", mOrderDetails.getGoodsName());

                String content = htmlContent;
                if (variables != null) {
                    for (Map.Entry<String, String> entry : variables.entrySet()) {
                        content = content.replace(entry.getKey(), entry.getValue());
                    }
                }
                mWebView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
            }catch (Exception e){
                e.printStackTrace();
            }

            return this;
        }

        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @Override
        public BaseDialog create() {
            return super.create();
        }

        @SingleClick
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_ui_confirm:
                    autoDismiss();
                    if (mListener != null) {
                        mListener.onConfirm(getDialog());
                    }
                    break;
                case R.id.tv_ui_cancel:
                    autoDismiss();
                    if (mListener != null) {
                        mListener.onCancel(getDialog());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public interface OnListener {

        /**
         * 点击确定时回调
         */
        void onConfirm(BaseDialog dialog);

        /**
         * 点击取消时回调
         */
        default void onCancel(BaseDialog dialog) {}
    }

}